package com.dream.myqiyi.ui;

import java.util.ArrayList;

import com.dream.myqiyi.BaseApp;
import com.dream.myqiyi.R;
import com.dream.myqiyi.dao.NoteModel;
import com.dream.myqiyi.dao.NotebookModel;
import com.dream.myqiyi.service.ApplicationContext;
import com.dream.myqiyi.service.NoteService;
import com.dream.myqiyi.service.NotebookService;
import com.dream.myqiyi.util.StringUtils;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class NotebookSelectActivity extends Activity {
	private String notebookGuid;
	
	private TextView etSelectNotebookName;
	
	// search
	private ListView searchList = null;
	private String searchKeyword;
	private ArrayList<NotebookModel> searchResult = new ArrayList<NotebookModel>();
	private NotebookSelectAdapter searchAdapter;		// 数据适配器
	private AutoCompleteTextView searchAutoEdit;//搜索文本框
	private RelativeLayout newNotebookLayout;
	private TextView newNoteBookText;

	// all
	private ListView allList;
	private ArrayList<NotebookModel> notebookList = new ArrayList<NotebookModel>();
	private NotebookSelectAdapter allAdapter;

	private static final int DIALOG_FIND = 2;
	
	NoteModel currNote;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notebook_select_activity);

		initUI();
		
		initUIData();

		doUpdate();
	}
	
	private void initUIData() {
		NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
		NotebookService nbSrv = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
		currNote = noteSrv.getCurrNoteModel();
		NotebookModel nb = null;
		if (currNote != null) {
			nb = nbSrv.getNotebook(currNote.getNotebookGuid());
		}
		if (nb == null) {
			nb = nbSrv.getCurrNotebook();	
		}
		notebookGuid = nb.getGuid();
		etSelectNotebookName.setText(nb.getName());
		
		updateUIData(false);
	}
	private void updateUIData(boolean isSearch) {
		if (isSearch) {
			newNotebookLayout.setVisibility(View.VISIBLE);
			searchList.setVisibility(View.VISIBLE);
			allList.setVisibility(View.GONE);
		} else {
			newNotebookLayout.setVisibility(View.GONE);
			searchList.setVisibility(View.GONE);
			allList.setVisibility(View.VISIBLE);
		}

	}
	private void initUI() {
		// 当前记事本
		etSelectNotebookName = (TextView)findViewById(R.id.selected_notebook_name_tv);
		// back
		findViewById(R.id.back_button).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (!notebookGuid.equals(currNote.getGuid())) {
					currNote.setNotebookGuid(notebookGuid);
					NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
					noteSrv.saveNote(currNote);
				}

				Intent intent = new Intent(NotebookSelectActivity.this, NoteInfoActivity.class);
				NotebookSelectActivity.this.setResult(NoteInfoActivity.NOTEBOOK_SELECTED_RESULT, intent);
				NotebookSelectActivity.this.finish();
			}
		});
		// search
		findViewById(R.id.search_button).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				searchKeyword = searchAutoEdit.getText().toString();
				if (searchKeyword.equals("")) {
					BaseApp.showToast("请输入您要查找的内容");
				} else {
					//请求数据(从新执行一个任务)
					new SearchNotebookTask().execute("");
				}
				
				// TODO 处理搜索结果
			}
		});
		
		//搜索文本框
		searchAutoEdit=(AutoCompleteTextView) findViewById(R.id.search_Keywords);
		searchAutoEdit.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable s) {
				searchKeyword = s.toString();
				if (StringUtils.isNull(searchKeyword)) {
					updateUIData(false);
				} else {
					updateUIData(true);
					new SearchNotebookTask().execute("");
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			} 
		});
		//搜索结果
		newNotebookLayout = (RelativeLayout)findViewById(R.id.add_no_search_layout);
		findViewById(R.id.add_no_search_btn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				NotebookService nbSrv = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
				NotebookModel nb = nbSrv.addNotebook(newNoteBookText.getText().toString());
				setNotebook(nb);
				newNotebookLayout.setVisibility(View.GONE);
				new SearchNotebookTask().execute("");
			}
		});
		newNoteBookText = (TextView)findViewById(R.id.no_search_tv);
		
		searchList=(ListView) this.findViewById(R.id.searchlist);
		searchAdapter = new NotebookSelectAdapter(NotebookSelectActivity.this, R.layout.list_item_single_select, searchResult);
		searchList.setAdapter(searchAdapter);
		searchList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				NotebookModel item = searchAdapter.getItem(position);
				notebookGuid = item.getGuid();
				setNotebook(item);
				
				// 选中后直接返回
				if (!notebookGuid.equals(currNote.getGuid())) {
					currNote.setNotebookGuid(notebookGuid);
					NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
					noteSrv.saveNote(currNote);
				}

				Intent intent = new Intent(NotebookSelectActivity.this, NoteInfoActivity.class);
				NotebookSelectActivity.this.setResult(NoteInfoActivity.NOTEBOOK_SELECTED_RESULT, intent);
				NotebookSelectActivity.this.finish();

			}
	
		});
		
		
		// 所有记事本
		allList = (ListView)findViewById(R.id.notebook_list);
		allAdapter = new NotebookSelectAdapter(NotebookSelectActivity.this, R.layout.list_item_single_select, notebookList);
		allList.setAdapter(allAdapter);
		allList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				NotebookModel item = allAdapter.getItem(position);
				notebookGuid = item.getGuid();
				setNotebook(item);
				//updateAdapter();
				
				// 选中后直接返回
				if (!notebookGuid.equals(currNote.getGuid())) {
					currNote.setNotebookGuid(notebookGuid);
					NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
					noteSrv.saveNote(currNote);
				}

				Intent intent = new Intent(NotebookSelectActivity.this, NoteInfoActivity.class);
				NotebookSelectActivity.this.setResult(NoteInfoActivity.NOTEBOOK_SELECTED_RESULT, intent);
				NotebookSelectActivity.this.finish();

			}
		});
	}
	
	private void setNotebook(NotebookModel nb) {
		etSelectNotebookName.setText(nb.getName());
		notebookGuid = nb.getGuid();
	}
	
	private void doUpdate() {
		new GetNotebooksTask().execute("");
	}

	private class GetNotebooksTask extends AsyncTask<String, String, String> {
		public String doInBackground(String... params) {		 
			// 获取数据
			loadData();
			return "";
		}

		@Override
		protected void onPreExecute() {
			//showDialog(DIALOG_LOAD);
			//loadmore_btn.setText("loading ...");
		}

		@Override
		public void onPostExecute(String Re) {
			//绑定LISTVIEW
			if(notebookList.size()==0){
				//emptytextView.setVisibility(View.VISIBLE);
			}
			else{
				updateAdapter();
			}
			
			allAdapter.notifyDataSetChanged();// 通知adapter数据变化
			//lvNotebook.setSelection(visibleLast - visibleCount + 1);
			
			//loadmore_btn.setText("Load More");
			//removeDialog(DIALOG_LOAD);
			NotebookService nbSrv = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
			if (nbSrv != null) {
				NotebookModel nb = nbSrv.getNotebook(notebookGuid);
				if (nb != null) {
					etSelectNotebookName.setText(nb.getName());
				}
			}
			
		}
	}

	private void loadData() {
		NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
		NotebookService nbSrv = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
		if (noteSrv == null || nbSrv == null) {
			return ;
		}
		NoteModel note = noteSrv.getCurrNoteModel();
		if (note != null) {
			notebookGuid = note.getNotebookGuid();
			notebookList.clear();
			notebookList.addAll(nbSrv.getAllNotebook());
		}		
	}

	//刷新适配器
	public void updateAdapter() {
		allAdapter.notifyDataSetChanged();
	}

	private class SearchNotebookTask extends AsyncTask<String, String, String> {
		private NotebookModel searchNotebook;
		public String doInBackground(String... params) {
			NotebookService nbSrv = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
			searchResult.clear();
			if (nbSrv != null) {
				ArrayList<NotebookModel> tags = nbSrv.getAllNotebook();
				for (NotebookModel tag : tags) {
					if (tag.getName().indexOf(searchKeyword) != -1) {
						if (tag.getName().equals(searchKeyword)) {
							searchNotebook = tag;
						}
						searchResult.add(tag);
					}
				}
			}
			return "";
		}

		@Override
		protected void onPreExecute() {
			//showDialog(DIALOG_FIND);
			searchNotebook = null;
			newNoteBookText.setVisibility(View.GONE);
		}

		@Override
		public void onPostExecute(String Re) {
			//绑定LISTVIEW
			//removeDialog(DIALOG_FIND);
			
            //通知适配器，发现改变操作
			searchAdapter.data = searchResult;
            searchAdapter.notifyDataSetChanged();	
            
            if (searchNotebook == null) {
            	newNotebookLayout.setVisibility(View.VISIBLE);
            	newNoteBookText.setText(searchKeyword);
            } else {
            	newNotebookLayout.setVisibility(View.GONE);
            }
		}
	}
	
	private class NotebookSelectAdapter extends ArrayAdapter<NotebookModel>{
		private ArrayList<NotebookModel> data;
        private int temp = -1;
        private int layoutId;

        public NotebookSelectAdapter(Activity a, int layout, ArrayList<NotebookModel> d) {
        	super(a, layout, d);
			data = d;
			layoutId = layout;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = getLayoutInflater().inflate(layoutId, null);  //解决办法： 每次都重新获取View
            TextView tvName = (TextView) convertView.findViewById(R.id.name_tv);
            RadioButton rbSelect = (RadioButton) convertView.findViewById(R.id.select_rb);
            rbSelect.setVisibility(View.GONE);
            rbSelect.setId(position);  //把position设为radioButton的id
            rbSelect.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    
                    if(isChecked){
                        //这段代码来实现单选功能
                        if(temp != -1){
                            RadioButton tempButton = (RadioButton) NotebookSelectActivity.this.findViewById(temp);
                            if(tempButton != null){
                               tempButton.setChecked(false);
                            }
                        }
                        
                        temp = buttonView.getId();
                        setNotebook(data.get(temp));
                        //Log.i(TAG,"you are women- -   " + isChecked + "   " + temp);
                        
                    }
                }
            });
            
            //这里实现单选框选的回显，解决了单选框移出屏幕范围未选中状态
            if(temp == position){
            	rbSelect.setChecked(true);
            }
            
            tvName.setText(data.get(position).getName());
            if (data.get(position).getGuid().equals(notebookGuid)) {
            	rbSelect.setChecked(true);
            } else {
            	rbSelect.setChecked(false);
            }
            return convertView;
        }
    }

	// 弹出"查看"对话框
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_FIND: {
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("正在查找...请稍候");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
		}
		return null;
	}

}
